<?php

namespace App\Models;

use Encore\Admin\Traits\AdminBuilder;
use App\Models\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Request;

class Cate extends Model
{
	use AdminBuilder, ModelTree ;
	protected $casts = ['sets'=>'json','extend' => 'json'];  

	
    protected static function boot() {    
        parent::boot();
        

        static::saved(function($model) {
			if(!empty($model->xapp_id)){
				$model->removeCache($model->xapp_id);
			}else{
				$model->removeCache();
			}
        });

        static::deleted(function ($model) {
			if(!empty($model->xapp_id)){
				$model->removeCache($model->xapp_id);
			}else{
				$model->removeCache();
			}
        });
    }


    /**
     * Create a new Eloquent model instance.
     *
     * @param array $attributes
     */
    public function __construct($xapp_id = 0)
    {
        if($xapp_id){
			static::addGlobalScope('avaiable',function(Builder $builder) use($xapp_id){
				$builder->where('xapp_id',$xapp_id);
			});
		}
        parent::__construct();
    }


    /**
     * {@inheritdoc}
     */
    public function delete()
    {
        $ids = $this->getnodeids($this->getKey());
		if($ids && count($ids)>1){
			unset($ids[0]);
			if($ids) $this->whereIn('id',$ids)->delete();
		}
        return parent::delete();
    }

    /**
     * determine if enable menu bind permission.
     *
     * @return bool
     */

 
    public function scopeStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    public function scopeCate($query, $id,$xapp_id=0)
    {
        if($id){
			$ids = $this->getnodeids($id,$xapp_id);
			return $query->whereIn('id', $ids);
		}
    }

    public function scopeRoot($query, $xapp_id)
    {
        return $query->where('xapp_id', $xapp_id);
    }  



	public function xapp()
	{
		return $this->belongsTo(\App\Models\Xapp::class, 'xapp_id','id');
	}

	public function removeCache($xapp_id='')
    {
		$xapp = get_xapp($xapp_id);
		if($xapp && empty($xapp_id)){
			foreach($xapp as $v){
				\Cache::forget('sys_table_cates_'.$v['name']);
			}
		}elseif(!empty($xapp)){
			\Cache::forget('sys_table_cates_'.$xapp['name']);
		}
    }

}
